import { CheckOutlined, CloseOutlined, LoadingOutlined } from '@ant-design/icons';
import { Button, Input, Select, Spin } from 'antd';
import dayjs from 'dayjs';
import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';

import type { Status } from '@/store/format';
import store from '@/store/format';

import styles from './index.less';

const Index = () => {
  const [cacheDir, setCacheDir] = useState(localStorage.getItem('videoCacheDir'));
  const {
    originFiles,
    formatStatus,
    currentEncoderList,
    currentEncoder,
    targetFormat,
    currentFormat,
    setStore
  } = store;
  const antIcon = (
    <LoadingOutlined
      style={{
        fontSize: 24
      }}
      spin
    />
  );
  const formatVideo = () => {
    const files = originFiles.map((file) => {
      return {
        id: file.lastModified,
        name: file.name,
        path: file.path
      };
    });
    setStore({ formatStatus: Array(originFiles.length).fill('loading') });
    window.api.formatVideo(
      {
        fileList: files,
        format: currentFormat,
        encoder: currentEncoder,
        cacheDir: ''
      },
      (res) => {
        const index = originFiles.findIndex((file) => file.lastModified === res.id);
        formatStatus[index] = res.status as Status;
        console.log(formatStatus, res, '进度');
        setStore({ formatStatus: [...formatStatus] });
      }
    );
  };
  const renderFormatStatus = useCallback(
    (file: File, index: number) => {
      switch (formatStatus[index]) {
        case 'pending':
          return <div></div>;
        case 'loading':
          return <Spin indicator={antIcon} />;
        case 'success':
          return (
            <div>
              <CheckOutlined style={{ color: '#3ce43c ' }} />
            </div>
          );
        case 'error':
          return (
            <div>
              <CloseOutlined style={{ color: '#e43c3c ' }} />
            </div>
          );
      }
    },
    [formatStatus]
  );
  return (
    <div className={styles.content}>
      <div className={styles.workWarp}>
        <div className={styles.selectFileBox}>
          <label>
            <div className={styles.selectFileBtn}>选择文件</div>
            <input
              style={{ display: 'none' }}
              type="file"
              multiple
              accept=".mp4,.flv,.avi,.mov,.flv,.3gp,.f4v"
              onChange={(e) => {
                const files = Object.values(e.target.files || {});
                setStore({ originFiles: [...originFiles, ...files] });
                console.log(e.target.files, files);
              }}
            />
          </label>
        </div>
        <div>
          <div className={styles.fileListHead}>
            <div>文件名</div>
            <div>日期</div>
            <div>大小</div>
          </div>
          {originFiles.map((file, index) => {
            return (
              <div key={index} className={styles.fileItem}>
                <div>{file.name}</div>
                <div>{dayjs(file.lastModified, 'x').format('YYYY年MM月DD日 HH:mm')}</div>
                <div>{`${(file.size / 1024 / 1024).toFixed(2)}MB`}</div>
                <div className={styles.formatStatus}>{renderFormatStatus(file, index)}</div>
              </div>
            );
          })}
        </div>
      </div>
      <div className={styles.footer}>
        <div className={styles.row}>
          <div className={styles.formItem}>
            <span>目标格式：</span>
            <Select
              value={currentFormat}
              options={targetFormat.map((item) => ({
                label: item.name,
                value: item.name,
                encoder: item.encoder
              }))}
              onChange={(value, option: any) => {
                setStore({
                  currentFormat: value,
                  currentEncoderList: option.encoder,
                  currentEncoder: option.encoder[0].value
                });
                console.log(store.currentEncoder, currentEncoder);
              }}
            />
          </div>
          <div className={styles.formItem}>
            <span>编解码器：</span>
            <Select
              value={currentEncoder}
              options={currentEncoderList}
              onChange={(value) => {
                setStore({ currentEncoder: value });
              }}
            />
          </div>
          <div className={styles.formItem}>
            <span>存储路径：</span>
            <Input
              readOnly
              value={cacheDir?.split('/').at(-1)}
              onClick={async () => {
                const data = await window.api.openDirectory({
                  properties: ['openDirectory'],
                  defaultPath: cacheDir || ''
                });
                data?.filePaths?.[0] && setCacheDir(data?.filePaths?.[0]);
              }}
            />
          </div>
        </div>
        <div className={styles.operateBtn}>
          <Button onClick={() => formatVideo()}>开始转换</Button>
        </div>
      </div>
    </div>
  );
};
export default observer(Index);
